package com.ilovetolearn.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.adobe.serialization.json.JSONEncoder;
	import com.ilovetolearn.business.SaveDataDelegate;
	import com.ilovetolearn.event.SaveWordEvent;
	import com.ilovetolearn.model.ModelLocator;
	import com.ilovetolearn.vo.SaveDataVo;
	import com.ilovetolearn.vo.WordVo;

	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class SaveWordCommand implements ICommand, IResponder
	{
		private var _model:ModelLocator=ModelLocator.getInstance();
		private var delegate:SaveDataDelegate;

		public function SaveWordCommand()
		{
			delegate=new SaveDataDelegate(this);
		}

		public function execute(event:CairngormEvent):void
		{
			var vo:SaveDataVo=(event as SaveWordEvent).vo;
			if (vo.data == null)
			{
				vo.data=new ArrayCollection();
			}
			for (var i:Number=0; i < _model.wordAc.length; i++)
			{
				var word:WordVo=_model.wordAc.getItemAt(i) as WordVo;
				var obj:Object=new Object();
				obj.wordprogress=word.wordprogress + 10;
				obj.wordid=word.wordid;
				vo.data.addItem(obj);
			}
			delegate.saveData(vo);
		}

		public function result(data:Object):void
		{
			var result:XML=new XML(ResultEvent(data).result);
			trace(result);
			var json:Object=new Object();
			json=JSON.decode(result);
			trace("保存结果：" + result);
			var resultcode:String=json.resultcode;
			trace("resultcode=" + resultcode);
			var errormsg:String=json.errormsg;
			trace("errormsg=" + errormsg);
			if (resultcode == "0")
			{
				_model.curState="WordFinishState";
			}
			else
			{
				Alert.show(errormsg);
			}
		}

		public function fault(info:Object):void
		{
			Alert.show(FaultEvent(info).toString());
		}
	}
}